// API配置文件
const API_BASE_URL = 'http://localhost:8080';

// 通用请求方法
async function apiRequest(endpoint, options = {}) {
    const url = `${API_BASE_URL}${endpoint}`;
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
        },
    };

    try {
        const response = await fetch(url, { ...defaultOptions, ...options });
        const data = await response.json();
        
        if (response.ok) {
            return data;
        } else {
            throw new Error(data.message || '请求失败');
        }
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}

// 会话管理API
const SessionAPI = {
    // 获取所有会话列表
    async getSessions(page = 1, size = 20) {
        return apiRequest(`/ai/sessions?page=${page}&size=${size}`);
    },

    // 创建新会话
    async createSession() {
        return apiRequest('/ai/sessions', {
            method: 'POST'
        });
    },

    // 获取指定会话详情
    async getSession(sessionId) {
        return apiRequest(`/ai/sessions/${sessionId}`);
    },

    // 更新会话标题
    async updateSession(sessionId, title) {
        return apiRequest(`/ai/sessions/${sessionId}`, {
            method: 'PUT',
            body: JSON.stringify({ title })
        });
    },

    // 删除会话
    async deleteSession(sessionId) {
        return apiRequest(`/ai/sessions/${sessionId}`, {
            method: 'DELETE'
        });
    }
};

// AI对话API
const ChatAPI = {
    // AI对话
    async chat(userInput, sessionId) {
        return apiRequest('/ai/chat', {
            method: 'POST',
            body: JSON.stringify({
                user_input: userInput,
                session_id: sessionId
            })
        });
    }
};

// 对话历史API
const HistoryAPI = {
    // 获取会话对话历史
    async getConversations(sessionId, page = 1, size = 50) {
        return apiRequest(`/ai/sessions/${sessionId}/conversations?page=${page}&size=${size}`);
    },

    // 搜索对话内容
    async searchConversations(keyword, sessionId = null, page = 1, size = 20) {
        const body = { keyword, page, size };
        if (sessionId) {
            body.session_id = sessionId;
        }
        
        return apiRequest('/ai/search', {
            method: 'POST',
            body: JSON.stringify(body)
        });
    },

    // 获取会话统计信息
    async getSessionStatistics(sessionId) {
        return apiRequest(`/ai/sessions/${sessionId}/statistics`);
    }
};

// 导出API对象
window.SessionAPI = SessionAPI;
window.ChatAPI = ChatAPI;
window.HistoryAPI = HistoryAPI; 